/*
 * Licensed to Nanjing RedOrange Co. ltd (RedOrange) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * RedOrange licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package redora.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;

/**
 * Often a file, resource can be located in several places because
 * Redora allows custom versions of files. So, when looking for a
 * file, first the custom version should be considered. If not
 * found the a local source version of Redora should be checked,
 * this is necessary when you develop Redora itself,
 * it should get the latest version.
 * If those not exist, it will look for the file in the classpath.<br>
 * In all cases an InputStream to the needed file is returned.
 */
public class ResourceFileHandler {
    private static Logger l = Logger.getLogger("redora.util"
                + ".ResourceFileHandler");

    private final static String LOCAL_UPGRADE_PATH = "src"
                + File.separator + "main" + File.separator + "resources"
                + File.separator + "upgrade" + File.separator;
    private final static String RESOURCE_UPGRADE_PATH = "/upgrade/";
    private final static String WEB_RESOURCE_UPGRADE_PATH = "/WEB-INF"
                + RESOURCE_UPGRADE_PATH;

    private final static String CUSTOM_POLICY_PATH = "src"
                + File.separator + "main" + File.separator + "resources"
                + File.separator + "policies" + File.separator;
    private final static String REDORA_POLICY_PATH = ".." + File.separator
                + "p-api" + File.separator + "src" + File.separator + "main"
                + File.separator + "resources" + File.separator + "policies"
                + File.separator;
    private static final String RESOURCE_POLICY_PATH = "/policies/";
    private static final String WEB_RESOURCE_POLICY_PATH = "/WEB-INF"
                + RESOURCE_POLICY_PATH;

    /**
     * Searches source by source until it finds your file.
     *
     * @param sources Files and Strings. String will be consider
     * a locator on the classpath.
     * @return Null or the requested inputstream
     */
    public static InputStream find(Object[] sources, ServletContext context)
              throws FileNotFoundException {
        for (Object source : sources) {
            if (source instanceof File) {
                if (((File)source).exists()) {
                    return new FileInputStream((File)source);
                }
                l.log(Level.INFO, "Can't find file "
                        + ((File)source).getAbsolutePath());
            } else if (source instanceof String) {
                String finalSource = (String)source;
                if (context == null) {
                    InputStream in = ResourceFileHandler
                    .class.getResourceAsStream(finalSource);
                    if (in != null) {
                        return in;
                    }
                } else {
                    finalSource = "/WEB-INF" + finalSource;
                    InputStream in = context.getResourceAsStream(finalSource);
                    if (in != null) {
                        return in;
                    }
                }
                l.log(Level.INFO, "Can't find resource " + finalSource);
            }
        }
        return null;
    }

    /**
     * Finds the file. First it will try the local src/main/resources/upgrade
     * dir. Then it will try the classpath in /upgrade
     *
     * @param fileName filename without path inluding the .sql suffix.
     * @return Null or the Inputstream.
     */
    public static InputStream findUpgradeFile(String fileName,
            ServletContext context) throws FileNotFoundException {
        Object[] sources = {new File(LOCAL_UPGRADE_PATH + fileName),
                RESOURCE_UPGRADE_PATH + fileName,
                WEB_RESOURCE_UPGRADE_PATH + fileName};
        return find(sources, context);
    }

    /**
     * Locates AntiSamy policy files. The user can provide a
     * custom policy file in his resources/policies directory.
     * Else the local Redora policies directory is checked.
     * And finally the classpath in policies.
     * @param policy The policy file name including the .xml suffix.
     * @return Null or the InpitStream
     */
    public static InputStream findPolicy(String policy)
                 throws FileNotFoundException {
        Object[] sources = {new File(CUSTOM_POLICY_PATH + policy),
                new File(REDORA_POLICY_PATH + policy), RESOURCE_POLICY_PATH
                + policy, WEB_RESOURCE_POLICY_PATH};
        //Object[] sources = {new File(CUSTOM_POLICY_PATH + policy),
        //new File(REDORA_POLICY_PATH + policy), RESOURCE_POLICY_PATH
        //+ policy, WEB_RESOURCE_POLICY_PATH, "/p-api-0.1.3-SNAPSHOT.jar"
        //+ RESOURCE_POLICY_PATH + policy};
        return find(sources, null);
    }
}
